﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace EasyTrader
{
    using PriceWaveList = List<EasyTrader.Wave.PriceWave>;
    using PricePointList = List<EasyTrader.Wave.PricePoint>;

    public partial class FutOptChartFrm : System.Windows.Forms.Form
    {
        int curChartType = 0;
        // Wave Manager
        private EasyTrader.Wave.WaveManager m_WaveManager = new EasyTrader.Wave.WaveManager();
        public EasyTrader.Wave.WaveManager WaveManager
        {
            get { return m_WaveManager; }
            set { m_WaveManager = value; }
        }

        // Cybos Plus Data Set Member
        private ETDataSet m_CPDataSet = null;
        public EasyTrader.ETDataSet CPDataSet
        {
            get { return m_CPDataSet; }
            set { m_CPDataSet = value; }
        }
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private void InitTimer()
        {
            timer.Interval = GlobalVar.ChartRefreshInterval;
            timer.Tick += new EventHandler(OnTimerTick);
            timer.Start();
        }

        private void SetWaveOnChart(PriceWaveList a_WaveList)
        {
            // 먼저 이전에 모든 점들을 없애 준다.
            FutOptChartCtrl.Series["파동"].Points.Clear();
            for (int i = 0; i < a_WaveList.Count; i++)
            {
                EasyTrader.Wave.PriceWave wave = a_WaveList[i];
                //if (i == 0 && wave.Height() < GlobalVar.MinMainWaveHeight)
                //    continue;
                FutOptChartCtrl.Series["파동"].Points.AddXY(wave.StartX, wave.StartY);
                //FutOptChartCtrl.Series["파동"].Points[i].AxisLabel = wave.StartPoint.XValue.ToString();
                // 파동은 마지막 점을 한번 더 넣어 준다.
                if (i == a_WaveList.Count - 1)
                {
                    FutOptChartCtrl.Series["파동"].Points.AddXY(wave.EndX, wave.EndY);
                    //newSeries.Points[i + 1].AxisLabel = wave.EndPoint.XValue.ToString();
                }
            }
        }
        private void InitControl()
        {
            FutOptChartCtrl.Series["지수"].ToolTip = "#VALX : #VAL";
            FutOptChartCtrl.Series["파동"].ToolTip = "#VALX : #VAL";
            cbShowWave.Checked = true;
            cbShowPrice.Checked = false;
        }
        // 여기서 차트를 갱신해 준다.
        private void OnTimerTick(object sender, EventArgs e)
        {
            // 차트에 데이터를 대응시켜 준다.
            SetChartData();
            // 파동을 그려준다.
            if (m_WaveManager != null)
            {
                // 파동을 만들어 놓는다.
                m_WaveManager.MakeWaveListFromFutOptChart();
                PriceWaveList curWaveList = m_WaveManager.ArragedWaveList;
                SetWaveOnChart(curWaveList);
            }
        }

        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null)
                return;

            FutOptChartCtrl.Series["지수"].Points.Clear();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            double maxValue = -10000.0;
            double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            int minIndex = 0;
            int maxIndex = 0;
            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["고가"] == DBNull.Value)
                        continue;
                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    closeValue = Convert.ToDouble(row["종가"]);
                    if (highValue == 0 || lowValue == 0 || openValue == 0 || closeValue == 0)
                        continue;

                    if (curChartType == 0)
                    {
                        FutOptChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        FutOptChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutOptChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        FutOptChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutOptChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        FutOptChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutOptChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                    }

                    if (highValue != 0 && highValue > maxValue)
                    {
                        maxValue = highValue;
                        maxIndex = i;
                    }
                    if (lowValue != 0 && lowValue < minValue)
                    {
                        minValue = lowValue;
                        minIndex = i;
                    }

                    if (i == rowCount - 1)
                    {
                        int p = 0;
                        p = p + 1;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            double valueHeight = maxValue - minValue;
            double ceilVal = Math.Ceiling(valueHeight);
            maxValue = minValue + ceilVal;

            if (maxValue >= minValue)
            {
                FutOptChartCtrl.ChartAreas["Price"].AxisY.Minimum = minValue;
                FutOptChartCtrl.ChartAreas["Price"].AxisY.Maximum = maxValue;
            }
        }

        public FutOptChartFrm()
        {
            InitializeComponent();
        }

        public FutOptChartFrm(ETDataSet a_DataSet)
        {
            InitializeComponent();
            m_CPDataSet = a_DataSet;
            InitControl();
        }

        private void InitChart()
        {
            FutOptChartCtrl.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            FutOptChartCtrl.BackSecondaryColor = System.Drawing.Color.White;
            FutOptChartCtrl.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutOptChartCtrl.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            FutOptChartCtrl.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutOptChartCtrl.BorderlineWidth = 2;
            FutOptChartCtrl.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            FutOptChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.Interval = 10;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.Interval = 10;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.Interval = 1;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.Interval = 1;

            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.IsClustered = true;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Perspective = 10;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.IsRightAngleAxes = false;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.WallWidth = 0;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Inclination = 15;
            FutOptChartCtrl.ChartAreas["Price"].Area3DStyle.Rotation = 10;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.IsLabelAutoFit = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = false;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsLabelAutoFit = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsStartedFromZero = false;
            //FutOptChartCtrl.ChartAreas["Price"].AxisY.LabelAutoFitMaxFontSize;
            FutOptChartCtrl.ChartAreas["Price"].BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            FutOptChartCtrl.ChartAreas["Price"].BackSecondaryColor = System.Drawing.Color.White;
            FutOptChartCtrl.ChartAreas["Price"].BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutOptChartCtrl.ChartAreas["Price"].BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutOptChartCtrl.ChartAreas["Price"].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutOptChartCtrl.ChartAreas["Price"].Position.Auto = true;
            //FutOptChartCtrl.ChartAreas["Price"].Position.Height = 80F;
            //FutOptChartCtrl.ChartAreas["Price"].Position.Width = 80F;
            //FutOptChartCtrl.ChartAreas["Price"].Position.X = 5F;
            //FutOptChartCtrl.ChartAreas["Price"].Position.Y = 10F;
            FutOptChartCtrl.ChartAreas["Price"].ShadowColor = System.Drawing.Color.Transparent;
            if (GlobalVar.FutOptChartType == 0)
            {
                FutOptChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                comboFutOptChartType.SelectedIndex = 0;
            }
            else
            {
                FutOptChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                comboFutOptChartType.SelectedIndex = 1;
            }

            FutOptChartCtrl.Series[0]["PriceUpColor"] = "Red";
            FutOptChartCtrl.Series[0]["PriceDownColor"] = "Blue";
            FutOptChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisX.IsMarginVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.IsEndLabelVisible = true;
            FutOptChartCtrl.ChartAreas["Price"].AxisY.IsMarginVisible = true;
            //FutOptChartCtrl.Series[0].Color = Color.Red;
            //DataPointCustomProperties aa = FutOptChartCtrl.Series[0]["PriceUpColor"];
        }

        private void FutOptChartFrm_Load(object sender, EventArgs e)
        {
            InitChart();
            InitTimer();
            curChartType = GlobalVar.FutOptChartType;
            m_WaveManager.EasyTraderDataSet = m_CPDataSet;
        }

        private void FutOptChartFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Stop();
        }

        private void comboFutOptChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            curChartType = comboFutOptChartType.SelectedIndex;
            if (curChartType != -1)
            {
                if (curChartType == 0)
                {
                    FutOptChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                }
                else
                {
                    FutOptChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                }
                SetChartData();
                FutOptChartCtrl.Invalidate();
            }
        }

        private void cbShowWave_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowWave.Checked)
            {
                FutOptChartCtrl.Series["파동"].Enabled = true;
            }
            else
            {
                FutOptChartCtrl.Series["파동"].Enabled = false;
            }
        }

        private void cbShowValue_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutOptChartCtrl.Series.FindByName("지수");
            if (series == null)
                return;
            if (cbShowPrice.Checked == true)
            {
                FutOptChartCtrl.Series["지수"].IsValueShownAsLabel = true;
                FutOptChartCtrl.Series["지수"].Label = "#VALX : #VAL{G5}";
            }
            else
            {
                FutOptChartCtrl.Series["지수"].IsValueShownAsLabel = false;
                FutOptChartCtrl.Series["지수"].Label = "";
            }
        }

        private void buttonExport_Click(object sender, EventArgs e)
        {
            EasyTrader.Signal.DirectionDetector director = new EasyTrader.Signal.DirectionDetector();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            director.SetChartData(0, 10, dataTable, "종가", false);
            director.ShowForecasting("3");
            director.ExportChartData();
            EasyTrader.Signal.ForecastingInfo foreInfo = director.GetForecastingInfoBeginEnd(dataTable, "종가", "3", 0, 10, false);
        }
    }
}
